package com.wk.wanjetpack.net

import android.util.Log
import androidx.paging.PagingSource
import com.wk.base.LOGTAG
import com.wk.base.PAGE_SIZE
import com.wk.base.START_PAGE
import com.wk.wanjetpack.bean.Article
import com.wk.wanjetpack.db.AppDataBase
import kotlinx.coroutines.delay

/**
 * @author peng
 * @date 2021/1/20
 * 说明
 */
class ArticleDataSource constructor(private val api:IApi) : PagingSource<Int,Article>(){

    val articleDao = AppDataBase.instance.articleDao

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Article> {
        val pageIndex = params.key?: START_PAGE
        return try {
            delay(1000)
            var listData = try {
                api.getArticles(pageIndex).data.datas
            }catch (e:Exception){
                Log.e(LOGTAG, "load: failed ${e.message}")
                emptyList()
            }
            if (listData.isNullOrEmpty()){
                try {
                    listData = articleDao.getArticlesByPage(pageIndex)
                }catch (e:Exception){
                    Log.e(LOGTAG, "loadDb: failed ${e.message}")
                }
            }else{
                listData.map { it.pageIndex = pageIndex }
                articleDao.insertArticles(listData)
            }
            LoadResult.Page(
                data = listData,
                prevKey = if (pageIndex == START_PAGE) null else pageIndex-1,
                nextKey = if (listData.isEmpty()) null else pageIndex+1
            )
        }catch (e:Exception){
            LoadResult.Error(e)
        }
    }

}